<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

    public function index(){
    	
        // json_decode   	
    	#$json = I('hook','','');
        $json = str_replace(array("\n","\r"),"\\n",$json);
        $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json);
        $json = preg_replace('/(,)\s*}$/','}',$json);

        #error_log($json);

    	$json = json_decode($json);
        // check password.
        if($json->{'password'} != 'ogph_123'){
           die("error.");
        }
        #error_log("fetch " . $repo_name . " start.");
        // set vars.
        $repo_name = $json->{'push_data'}->{'repository'}->{'name'};
        $repo_http_url = $json->{'push_data'}->{'repository'}->{'url'};
        #$repo_http_url = str_replace(array("http://"),"https://",$json->{'push_data'}->{'repository'}->{'homepage'}) . ".git";
        $local_repo_path = '/home/git/repos/' . $repo_name . '/';
        if(is_writable(RUNTIME_PATH) === false){
    		die('运行目录不可写');
    	}

        // execute git fetch.
        $this -> show('start');
        include_once './Application/Common/Api/Git.class.php';

        // clone git repo.
        if (file_exists($local_repo_path) === false) {
            \Git :: clone_remote($local_repo_path, $repo_http_url);                 
        }

        // fetch exist repo.
	$repo = \Git :: open($local_repo_path);
        dump($repo -> run('fetch origin'));
        dump($repo -> run('reset origin --hard'));
        #error_log("fetch " . $repo_name . " end.");
        $this -> show('end');
    }

}
